import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class testDB extends HttpServlet {

	

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {

    	response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
	    String title = "DB-Test";
	    out.println("<title>DB_Test</title>");
        out.println("</head>");
        out.println("<body>");
        out.println ("<table border='1'>");
        out.println ("<tr>");
        out.println ("<td>ID</td><td>VALUE</td>");
        out.println ("</tr>");
    	
    	
    	Connection connection;
    	
    	try {
    		String driverName = "org.postgresql.Driver";
    		String url="jdbc:postgresql:waiDB";
   			String username="wai_usr"; 
   			String password="wai"; 
   			String query="";
    		
    		Class.forName(driverName);
    		connection = DriverManager.getConnection(url, username, password);
    		Statement stmt = connection.createStatement();
    		ResultSet rs = stmt.executeQuery ("select * from test;");
    		while (rs.next()) {
    	        out.println ("<tr>");
    	        out.println ("<td>");
    			out.println (rs.getInt("id"));
    	        out.println ("</td>");
    	        out.println ("<td>");
    			out.println (rs.getString("value"));
    	        out.println ("</td>");
    	        out.println ("</tr>");
    		}

    		rs = stmt.executeQuery("select max(id)+1 as cnt from test;");
    		if (rs.next()) {
    			query = "insert into test (id, value) VALUES (" + rs.getInt("cnt") + ", 'blabla');";
    			System.out.println ("Query: " + query);
    			stmt.executeUpdate(query);
    		}
    		connection.close();
    		
    	} catch (ClassNotFoundException e) {
    		System.out.println ("ClassNotFoundException:");
    		e.printStackTrace();
    	} catch (SQLException e) {
    		System.out.println ("SQLException:");
    		e.printStackTrace();
    	} catch (Exception e) {
    		System.out.println ("Exception:");
    		e.printStackTrace();
    	}
    	
        out.println ("</table>");
        out.println("</body>");
        out.println("</html>");
    }
}



